# -*- coding: utf-8 -*-
"""
Created on Mon Sep 26 09:16:22 2022

@author: Administrator
"""

import cv2
import numpy as np

deta = 5

def getBinImg(img):
    #Color to Gray
    grayImg = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
    #Gray to Binary
    binImg = grayImg.copy()
    height = grayImg.shape[0]
    width = grayImg.shape[1]
    for i in range(height):
        for j in range(width):
            if grayImg[i][j] >100:
                binImg[i][j] = 0  #white
            else:
                binImg[i][j] = 1  #black
                
    return binImg

def getXstartEnd(colBlacks):
    xStart = -1
    xEnd = -1
    startFlag = 0 
    for i in range(len(colBlacks)):
        if (not startFlag) and (colBlacks[i]!=0):
            xStart = i - deta
            startFlag = 1
        print(colBlacks[i])
        if (startFlag) and colBlacks[i]==0:
            xEnd = i + deta
            break
    return xStart,xEnd
            
def getYstartEnd(rowBlacks):
    yStart = -1
    yEnd = -1
    startFlag = 0 
    for i in range(len(rowBlacks)):
        if (not startFlag) and (rowBlacks[i]!=0):
            yStart = i - deta
            startFlag = 1
        print(rowBlacks[i])
        if (startFlag) and rowBlacks[i]==0:
            yEnd = i + deta
            break
    return yStart,yEnd


img = cv2.imread('testdata/3_test.jpg')
binImg = getBinImg(img)

#print(np.sum(binImg))
#print(np.sum(binImg,axis=0))
colBlacks = np.sum(binImg,axis=0)
rowBlacks = np.sum(binImg,axis=1)
x_start,x_end = getXstartEnd(colBlacks)
y_start,y_end = getYstartEnd(rowBlacks)
#print(getYstartEnd(rowBlacks))
#print(getXstartEnd(colBlacks))
# print(img.shape)
# height = img.shape[0]
# width = img.shape[1]



#x->width
#y->height
# y_start = 60
# y_end = 139
# x_start =3
# x_end = 65
cropImg = img[y_start:y_end,x_start:x_end]
cv2.imwrite("cropImg.jpg",cropImg)

#print(np.sum(cropImg,axis=0))

